package cn.itsource.config;

import cn.itsource.adminConfig.AdminConfig;
import cn.itsource.mapper.LoginMapper;
import cn.itsource.mapper.RoleMapper;
import cn.itsource.pojo.domain.Login;
import cn.itsource.pojo.domain.Role;
import cn.itsource.utils.IdUtil;
import cn.itsource.utils.RConst;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @program fccar_tt
 * @Description
 * @Author TT
 * @Date 2024/09/09 20:01
 * @Version 1.0
 */
@Component
public class BootstrapListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AdminConfig adminConfig;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        Login login = loginMapper.selectOne(new LambdaQueryWrapper<Login>()
                .eq(Login::getUsername, adminConfig.getUsername())
                .eq(Login::getType, RConst.Num.INT_0));
        if(login==null){
            Login login1 = new Login();
            login1.setId(IdUtil.getSnowFlackId());
            login1.setUsername(adminConfig.getUsername());
            login1.setPassword(passwordEncoder.encode(adminConfig.getPassword()));
            login1.setType(RConst.Num.INT_0);
            login1.setAvatar(adminConfig.getAvatar());
            login1.setAdmin(RConst.Num.INT_1);
            login1.setNickName(adminConfig.getNickName());
            login1.setName(adminConfig.getName());
            login1.setCreateTime(new Date());
            loginMapper.insert(login1);
            //赋予角色
            Role role = roleMapper.selectOne(new LambdaQueryWrapper<Role>()
                    .eq(Role::getSn, adminConfig.getRoleSN()));
            //添加到中间表
            loginMapper.addRole(login1.getId(),role.getId(),IdUtil.getSnowFlackId());
        }
    }
}
